package com.delos.world.rpc;

import com.delos.hello.error.RpcException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.scheduling.annotation.Async;

import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author zouyaowen
 * @date 2020-04
 */
@Service
@Slf4j
public class WorldRpcImpl implements IWorldRpc {

    @Override
    public String world(String name) {
        log.info("world方法执行，参数name=[{}]", name);
        RpcContext context = RpcContext.getContext();
        String remoteAddressString = context.getRemoteAddressString();
        String localAddressString = context.getLocalAddressString();
        String methodName = context.getMethodName();
        Object[] arguments = context.getArguments();
        log.info("methodName=[{}]", methodName);
        if ("hello".equals(name)) {
            throw new RpcException(200, "33333", remoteAddressString, localAddressString, methodName, arguments);
        }
        return "world" + name;
    }

    @Override
    @Async
    public CompletableFuture<String> asyncWorld(String name) {
        log.info("asyncWorld time=[{}]", LocalDateTime.now());
        log.info("asyncWorld，参数name=[{}]", name);
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("asyncWorld调用结束time=[{}]", LocalDateTime.now().toString());
        return CompletableFuture.completedFuture("asyncWorld" + name);
    }
}
